package com.xjscrm.console.service.customer.sop.impl;

import cn.hutool.core.bean.BeanUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.github.pagehelper.PageHelper;
import com.xjscrm.common.constant.ResponseMsg;
import com.xjscrm.common.entity.*;
import com.xjscrm.common.enums.RedisCacheKeyEnum;
import com.xjscrm.common.exception.BusinessException;
import com.xjscrm.common.result.ResponseCode;
import com.xjscrm.common.utils.DateUtil;
import com.xjscrm.common.utils.OrderByUtil;
import com.xjscrm.common.vo.grouppull.GroupPullData;
import com.xjscrm.common.vo.grouppull.GroupRule;
import com.xjscrm.common.vo.grouppull.GroupRuleInfo;
import com.xjscrm.common.vo.sop.*;
import com.xjscrm.console.mapper.*;
import com.xjscrm.console.param.BaseDto;
import com.xjscrm.console.param.SopTaskDeviceDto;
import com.xjscrm.console.param.operatePlan.EffectuateGroupDto;
import com.xjscrm.console.param.sop.*;
import com.xjscrm.console.param.user.ChildMerchatDto;
import com.xjscrm.console.param.wwDevice.WwDeviceQuery;
import com.xjscrm.console.service.common.user.UserService;
import com.xjscrm.console.service.customer.childUser.ChildMerchatService;
import com.xjscrm.console.service.customer.sop.SopService;
import com.xjscrm.console.service.customer.wwDevice.WwDeviceService;
import com.xjscrm.console.vo.*;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import java.util.stream.Stream;

@Service
public class SopServiceImpl implements SopService {

    @Autowired
    private SopTemplateMapper sopTemplateMapper;

    @Autowired
    private SopTaskMapper sopTaskMapper;

    @Autowired
    private SopTaskDeviceMapper sopTaskDeviceMapper;

    @Autowired
    private SopTaskCustomerMapper sopTaskCustomerMapper;

    @Autowired
    private WwDeviceMapper wwDeviceMapper;

    @Autowired
    private WwCustomerMapper wwCustomerMapper;

    @Autowired
    private WwGroupMapper wwGroupMapper;

    @Autowired
    private SopJobMapper sopJobMapper;

    @Autowired
    private WwDeviceService wwDeviceService;

    @Autowired
    private SopTaskDeviceConfigMapper sopTaskDeviceConfigMapper;

    @Autowired
    private UserService userService;

    @Autowired
    private ChildMerchatService childMerchatService;

    @Autowired
    private RedisTemplate redisTemplate;


    @Override
    public void addSopTemplate(SopTemplateDto sopTemplateDto) {

        if (sopTemplateDto.getMerId() == null) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.MERID_NULL);
        }
        if (sopTemplateDto.getOperatorType() == null) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "账号类型错误");
        }
        if (sopTemplateDto.getModel() == null) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "所属模块错误");
        }
        if (StringUtils.isBlank(sopTemplateDto.getName())) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "模版名称不能为空");
        }
        if (sopTemplateDto.getUnsubscribeSwitch() == null) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "退订开关(0-不开启；1-开启)不能为空");
        }
        if (sopTemplateDto.getPlanDataList() == null || sopTemplateDto.getPlanDataList().isEmpty()) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "发送计划不能为空");
        }

        //主账户操作保存主账号id
        if (sopTemplateDto.getOperatorType() == 0) {
            sopTemplateDto.setChildId(sopTemplateDto.getMerId());
        }
        if (sopTemplateDto.getChildId() == null) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "所属账号id(主账户操作保存主账号id)不能为空");
        }

        SopTemplate sopTemplate = new SopTemplate();
        BeanUtil.copyProperties(sopTemplateDto, sopTemplate);
        sopTemplate.setPlanDatas(JSONObject.toJSONString(sopTemplateDto.getPlanDataList()));

        sopTemplateMapper.add(sopTemplate);
    }


    @Override
    public void updateSopTemplate(SopTemplateDto sopTemplateDto) {

        if (sopTemplateDto.getMerId() == null) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.MERID_NULL);
        }
        if (sopTemplateDto.getId() == null) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.ID_NULL);
        }
        if (sopTemplateDto.getOperatorType() == null) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "账号类型错误");
        }
        if (sopTemplateDto.getModel() == null) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "所属模块错误");
        }
        if (StringUtils.isBlank(sopTemplateDto.getName())) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "模版名称不能为空");
        }
        if (sopTemplateDto.getUnsubscribeSwitch() == null) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "退订开关(0-不开启；1-开启)不能为空");
        }
        if (sopTemplateDto.getPlanDataList() == null || sopTemplateDto.getPlanDataList().isEmpty()) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "发送计划不能为空");
        }

        //主账户操作保存主账号id
        if (sopTemplateDto.getOperatorType() == 0) {
            sopTemplateDto.setChildId(sopTemplateDto.getMerId());
        }
        if (sopTemplateDto.getChildId() == null) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "所属账号id(主账户操作保存主账号id)不能为空");
        }

        SopTemplate sopTemplate = sopTemplateMapper.getById(sopTemplateDto.getId(), sopTemplateDto.getMerId());

        if (sopTemplate == null) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "未获取到该模版");
        }

        BeanUtil.copyProperties(sopTemplateDto, sopTemplate);
        sopTemplate.setPlanDatas(JSONObject.toJSONString(sopTemplateDto.getPlanDataList()));

        sopTemplateMapper.update(sopTemplate);
    }

    @Override
    public Object getSopTemplateList(SopTemplateQuery sopTemplateQuery) {

        if (sopTemplateQuery.getMerId() == null) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.MERID_NULL);
        }
        if (sopTemplateQuery.getOperatorType() == null) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "账号类型错误");
        }
        if (sopTemplateQuery.getModel() == null) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "所属模块不能为空");
        }

        if (sopTemplateQuery.getOperatorType() == 1 && sopTemplateQuery.getChildId() == null) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "子账号ID为空");
        }
        if (sopTemplateQuery.getModel() == 1) {
            sopTemplateQuery.setChildId(null);
        }
        //主账号查询个人模版，child_id传入主账号ID
        if (sopTemplateQuery.getModel() == 2) {
            if (sopTemplateQuery.getOperatorType() == 0 && sopTemplateQuery.getChildId() == null) {
                sopTemplateQuery.setChildId(sopTemplateQuery.getMerId());
            }
        }


        String orderBy = OrderByUtil.getOrderBy(sopTemplateQuery.getOrderByField(), sopTemplateQuery.isAsc());
        PageHelper.startPage(sopTemplateQuery.getCurrent(), sopTemplateQuery.getSize(), orderBy);

        List<SopTemplateVo> sopTemplateVoList = sopTemplateMapper.getSopTemplateList(sopTemplateQuery);
        if (sopTemplateVoList != null && !sopTemplateVoList.isEmpty()) {
            for (SopTemplateVo sopTemplateVo : sopTemplateVoList) {
                try {
                    sopTemplateVo.setPlanDataList(JSONObject.parseArray(sopTemplateVo.getPlanDatas(), PlanData.class));
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }


        return new MyPageInfo<>(sopTemplateVoList);
    }


    @Override
    public Object getSopTemplateDropDown(SopTemplateQuery sopTemplateQuery) {

        if (sopTemplateQuery.getMerId() == null) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.MERID_NULL);
        }
        if (sopTemplateQuery.getOperatorType() == null) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "账号类型错误");
        }
        if (sopTemplateQuery.getModel() == null) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "所属模块不能为空");
        }

        if (sopTemplateQuery.getOperatorType() == 1 && sopTemplateQuery.getChildId() == null) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "子账号ID为空");
        }
        if (sopTemplateQuery.getModel() == 1) {
            sopTemplateQuery.setChildId(null);
        }
        //主账号查询个人模版，child_id传入主账号ID
        if (sopTemplateQuery.getModel() == 2) {
            if (sopTemplateQuery.getOperatorType() == 0 && sopTemplateQuery.getChildId() == null) {
                sopTemplateQuery.setChildId(sopTemplateQuery.getMerId());
            }
        }

        List<SopTemplateVo> sopTemplateVoList = sopTemplateMapper.getSopTemplateList(sopTemplateQuery);

        ArrayList<Map> mapArrayList = new ArrayList<>();
        if (sopTemplateVoList != null && !sopTemplateVoList.isEmpty()) {
            for (SopTemplateVo sopTemplateVo : sopTemplateVoList) {
                HashMap<String, Object> map = new HashMap<>();
                map.put("label", sopTemplateVo.getName());
                map.put("value", sopTemplateVo.getId());
                mapArrayList.add(map);
            }
        }
        return mapArrayList;
    }

    @Override
    public Object getSopTemplateDetail(SopTemplateDto sopTemplateDto) {

        if (sopTemplateDto.getMerId() == null) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.MERID_NULL);
        }
        if (sopTemplateDto.getId() == null) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.ID_NULL);
        }

        SopTemplate sopTemplate = sopTemplateMapper.getById(sopTemplateDto.getId(), sopTemplateDto.getMerId());

        if (sopTemplate == null) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "未找到该素材");
        }

        SopTemplateVo sopTemplateVo = new SopTemplateVo();
        BeanUtil.copyProperties(sopTemplate, sopTemplateVo);

        if (!StringUtils.isBlank(sopTemplate.getPlanDatas())) {
            sopTemplateVo.setPlanDataList(JSONObject.parseArray(sopTemplate.getPlanDatas(), PlanData.class));
        }

        return sopTemplateVo;
    }


    @Override
    public void delSopTemplate(SopTemplateDto sopTemplateDto) {
        if (sopTemplateDto.getMerId() == null) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.MERID_NULL);
        }
        if (sopTemplateDto.getId() == null) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.ID_NULL);
        }
        sopTemplateMapper.delById(sopTemplateDto.getId(), sopTemplateDto.getMerId());
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void addSopTask(SopTaskDto sopTaskDto) {
        if (sopTaskDto.getMerId() == null) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.MERID_NULL);
        }
        if (sopTaskDto.getOperatorType() == null) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "账号类型错误");
        }
        if (!StringUtils.isBlank(sopTaskDto.getName())) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "任务名称不能为空");
        }
        if (sopTaskDto.getType() == null) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "类型不能为空");
        }
        if (sopTaskDto.getSopTaskDeviceDtoList() == null || sopTaskDto.getSopTaskDeviceDtoList().isEmpty()) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "生效机器人不能为空");
        }

        if (sopTaskDto.getUpdaterId() != null) {
            sopTaskDto.setCreaterId(sopTaskDto.getUpdaterId());
        }

        if (sopTaskDto.getType() == 1 && sopTaskDto.getHangerTigger() == null) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "手动sop,手动SOP触发条件不能为空");
        }
        if (sopTaskDto.getType() == 2 && sopTaskDto.getNewCustomerTigger() == null) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "新客sop,新客SOP触发条件不能为空");
        }
        if (sopTaskDto.getType() == 3 && sopTaskDto.getTagTigger() == null) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "标签sop,标签SOP触发条件不能为空");
        }
        if (sopTaskDto.getType() == 4 && sopTaskDto.getGroupTigger() == null) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "群sop,群SOP触发条件不能为空");
        }

        SopTask sopTask = new SopTask();
        BeanUtil.copyProperties(sopTaskDto, sopTask);
        int time = DateUtil.getTime();
        long id = IdWorker.getId();
        sopTask.setId(id);
        sopTask.setCreateTime(time);
        sopTask.setUpdateTime(time);


        if (sopTask.getType() == 1) {
            sopTask.setTrigger(JSONObject.toJSONString(sopTaskDto.getHangerTigger()));
        }
        if (sopTask.getType() == 2) {
            sopTask.setTrigger(JSONObject.toJSONString(sopTaskDto.getNewCustomerTigger()));
        }
        if (sopTask.getType() == 3) {
            sopTask.setTrigger(JSONObject.toJSONString(sopTaskDto.getTagTigger()));
        }
        if (sopTask.getType() == 4) {
            sopTask.setTrigger(JSONObject.toJSONString(sopTaskDto.getGroupTigger()));
        }

        sopTaskMapper.insert(sopTask);

        //插入sop任务和机器人关系
        for (SopTaskDeviceDto sopTaskDeviceDto : sopTaskDto.getSopTaskDeviceDtoList()) {
            SopTaskDevice sopTaskDevice = new SopTaskDevice();
            BeanUtil.copyProperties(sopTaskDeviceDto, sopTaskDevice);
            sopTaskDevice.setTaskId(id);
            sopTaskDevice.setMerId(sopTask.getMerId());
            sopTaskDevice.setType(sopTask.getType());
            sopTaskDeviceMapper.add(sopTaskDevice);
        }

        //插入sop任务和群/客户关系
        if (sopTask.getType() == 1) {
            if (sopTaskDto.getSopTaskCustomerDtoList() != null && !sopTaskDto.getSopTaskCustomerDtoList().isEmpty()) {

                for (SopTaskCustomerDto sopTaskCustomerDto : sopTaskDto.getSopTaskCustomerDtoList()) {
                    SopTaskCustomer sopTaskCustomer = new SopTaskCustomer();
                    BeanUtil.copyProperties(sopTaskCustomerDto, sopTaskCustomer);
                    sopTaskCustomer.setTaskId(id);
                    sopTaskCustomer.setMerId(sopTask.getMerId());
                    sopTaskCustomerMapper.add(sopTaskCustomer);
                }

            }
        }
    }

    @Override
    public Object getSopTaskList(SopTaskQuery sopTaskQuery) {

        if (sopTaskQuery.getMerId() == null) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.MERID_NULL);
        }
        if (sopTaskQuery.getOperatorType() == null) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "账号类型错误");
        }
        if (sopTaskQuery.getOperatorType() == 0) {
            sopTaskQuery.setChildId(sopTaskQuery.getMerId());
        }
        if (sopTaskQuery.getChildId() == null) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "操作账号为空");
        }

        //通过模版名获取模版ID
        if (!StringUtils.isBlank(sopTaskQuery.getTemplateName())) {
            //获取企业模版
            SopTemplateQuery sopTemplateQuery = new SopTemplateQuery();
            sopTemplateQuery.setMerId(sopTemplateQuery.getMerId());
            sopTemplateQuery.setName(sopTaskQuery.getTemplateName());
            sopTemplateQuery.setModel(1);
            List<SopTemplateVo> sopTemplateList = sopTemplateMapper.getSopTemplateList(sopTemplateQuery);
            List<Long> enterpriseTemplateIds = null;
            if (sopTemplateList != null && !sopTemplateList.isEmpty()) {
                enterpriseTemplateIds = sopTemplateList.stream().map(SopTemplateVo::getId).distinct().collect(Collectors.toList());
            }

            //获取个人模版
            SopTemplateQuery sopTemplateQuery1 = new SopTemplateQuery();
            sopTemplateQuery1.setMerId(sopTemplateQuery.getMerId());
            sopTemplateQuery1.setName(sopTaskQuery.getTemplateName());
            sopTemplateQuery1.setModel(2);
            sopTemplateQuery1.setChildId(sopTaskQuery.getChildId());
            List<SopTemplateVo> sopTemplateList1 = sopTemplateMapper.getSopTemplateList(sopTemplateQuery1);
            List<Long> personTemplateIds = null;
            if (sopTemplateList1 != null && !sopTemplateList1.isEmpty()) {
                personTemplateIds = sopTemplateList1.stream().map(SopTemplateVo::getId).distinct().collect(Collectors.toList());
            }
            List<Long> templateIds = new ArrayList<>();

            if (enterpriseTemplateIds == null && personTemplateIds == null) {
                return new MyPageInfo<>(null);
            }
            if (enterpriseTemplateIds == null && personTemplateIds != null) {
                templateIds = personTemplateIds;
            }
            if (enterpriseTemplateIds != null && personTemplateIds == null) {
                templateIds = enterpriseTemplateIds;
            }
            if (enterpriseTemplateIds != null && personTemplateIds != null) {
                templateIds = Stream.concat(enterpriseTemplateIds.stream(), personTemplateIds.stream()).collect(Collectors.toList());
            }


            if (templateIds.isEmpty()) {
                return new MyPageInfo<>(null);
            }
            sopTaskQuery.setTemplateIds(templateIds);
        }

        String orderBy = OrderByUtil.getOrderBy(sopTaskQuery.getOrderByField(), sopTaskQuery.isAsc());
        PageHelper.startPage(sopTaskQuery.getCurrent(), sopTaskQuery.getSize(), orderBy);

        List<SopTaskVo> sopTaskVoList = sopTaskMapper.getSopTaskList(sopTaskQuery);

        if (sopTaskVoList != null && !sopTaskVoList.isEmpty()) {
            for (SopTaskVo sopTaskVo : sopTaskVoList) {
                try {
                    //获取模版名
                    SopTemplate sopTemplate = sopTemplateMapper.getById(sopTaskVo.getTeaplateId(), sopTaskVo.getMerId());
                    if (sopTemplate != null) {
                        sopTaskVo.setTemplateName(sopTemplate.getName());
                        sopTaskVo.setTeplateModel(sopTemplate.getModel());
                    }

                    //设置触发条件列表


                    //获取sop和机器人关系
                    SopTaskDeviceQuery sopTaskDeviceQuery = new SopTaskDeviceQuery();
                    sopTaskDeviceQuery.setMerId(sopTaskVo.getMerId());
                    sopTaskDeviceQuery.setTaskId(sopTaskVo.getId());
                    List<SopTaskDeviceVo> sopTaskDeviceVoList = sopTaskDeviceMapper.getSopTaskDeviceList(sopTaskDeviceQuery);
                    if (sopTaskDeviceVoList != null && !sopTaskDeviceVoList.isEmpty()) {
                        for (SopTaskDeviceVo sopTaskDeviceVo : sopTaskDeviceVoList) {
                            try {
                                //获取机器人头像和昵称
                                WwDevice wwDevice = wwDeviceMapper.getById(sopTaskDeviceVo.getDeviceUniqueId(), sopTaskVo.getMerId());
                                if (wwDevice != null) {
                                    sopTaskDeviceVo.setDeviceName(wwDevice.getDeviceName());
                                    sopTaskDeviceVo.setDeviceHeadImageUrl(wwDevice.getHeadImgUrl());
                                }

                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                        }
                        sopTaskVo.setSopTaskDeviceVoList(sopTaskDeviceVoList);
                    }

                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }

        if (sopTaskVoList != null && !sopTaskVoList.isEmpty()) {
            for (SopTaskVo sopTaskVo : sopTaskVoList) {
                try {
                    //获取创建人
                    if (sopTaskVo.getOperatorType() != null && sopTaskVo.getOperatorType() == 0 && sopTaskVo.getCreaterId() != null) {
                        BaseDto baseDto = new BaseDto();
                        baseDto.setMerId(sopTaskVo.getCreaterId());
                        Merchant merchant = userService.getById(baseDto);
                        if (merchant != null) {
                            sopTaskVo.setCreateUserName(merchant.getUserName());
                        }
                    }
                    if (sopTaskVo.getOperatorType() != null && sopTaskVo.getOperatorType() == 1 && sopTaskVo.getCreaterId() != null) {
                        ChildMerchatDto childMerchatDto = new ChildMerchatDto();
                        childMerchatDto.setId(sopTaskVo.getCreaterId());
                        childMerchatDto.setMerId(sopTaskVo.getMerId());
                        MerchatChild merchatChild = childMerchatService.getById(childMerchatDto);
                        if (merchatChild != null) {
                            sopTaskVo.setCreateUserName(merchatChild.getUserName());
                        }
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }

        return new MyPageInfo<>(sopTaskVoList);
    }

    @Override
    public Object getSopTaskDetail(SopTaskDto sopTaskDto) {
        if (sopTaskDto.getMerId() == null) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.MERID_NULL);
        }
        if (sopTaskDto.getId() == null) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.ID_NULL);
        }

        SopTask sopTask = sopTaskMapper.getById(sopTaskDto.getId(), sopTaskDto.getMerId());

        if (sopTask == null) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "该sop任务不存在");
        }

        SopTaskVo sopTaskVo = new SopTaskVo();
        BeanUtil.copyProperties(sopTask, sopTaskVo);

        //获取模版名
        SopTemplate sopTemplate = sopTemplateMapper.getById(sopTaskVo.getTeaplateId(), sopTaskVo.getMerId());
        if (sopTemplate != null) {
            sopTaskVo.setTemplateName(sopTemplate.getName());
            sopTaskVo.setTeplateModel(sopTemplate.getModel());
        }

        //设置触发条件列表
        if (!StringUtils.isBlank(sopTaskVo.getTrigger())) {
            if (sopTaskVo.getType() == 1) {
                sopTaskVo.setHangerTigger(JSONObject.parseObject(sopTaskVo.getTrigger(), HangerTigger.class));
            }
            if (sopTaskVo.getType() == 2) {
                sopTaskVo.setNewCustomerTigger(JSONObject.parseObject(sopTaskVo.getTrigger(), NewCustomerTigger.class));
            }
            if (sopTaskVo.getType() == 3) {
                sopTaskVo.setTagTigger(JSONObject.parseObject(sopTaskVo.getTrigger(), TagTigger.class));
            }
            if (sopTaskVo.getType() == 4) {
                sopTaskVo.setGroupTigger(JSONObject.parseObject(sopTaskVo.getTrigger(), GroupTigger.class));
            }
        }

        //获取sop和机器人关系
        SopTaskDeviceQuery sopTaskDeviceQuery = new SopTaskDeviceQuery();
        sopTaskDeviceQuery.setMerId(sopTaskVo.getMerId());
        sopTaskDeviceQuery.setTaskId(sopTaskVo.getId());
        List<SopTaskDeviceVo> sopTaskDeviceVoList = sopTaskDeviceMapper.getSopTaskDeviceList(sopTaskDeviceQuery);
        if (sopTaskDeviceVoList != null && !sopTaskDeviceVoList.isEmpty()) {
            for (SopTaskDeviceVo sopTaskDeviceVo : sopTaskDeviceVoList) {
                try {
                    //获取机器人头像和昵称
                    WwDevice wwDevice = wwDeviceMapper.getById(sopTaskDeviceVo.getDeviceUniqueId(), sopTaskVo.getMerId());
                    if (wwDevice != null) {
                        sopTaskDeviceVo.setDeviceName(wwDevice.getDeviceName());
                        sopTaskDeviceVo.setDeviceHeadImageUrl(wwDevice.getHeadImgUrl());
                    }

                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
            sopTaskVo.setSopTaskDeviceVoList(sopTaskDeviceVoList);
        }

        //获取sop和客户或者群的关系
        if (sopTaskVo.getType() == 1) {
            SopTaskCustomerQuery sopTaskCustomerQuery = new SopTaskCustomerQuery();
            sopTaskCustomerQuery.setMerId(sopTaskVo.getMerId());
            sopTaskCustomerQuery.setTaskId(sopTaskVo.getId());
            List<SopTaskCustomerVo> sopTaskCustomerVoList = sopTaskCustomerMapper.getSopTaskCustomerList(sopTaskCustomerQuery);
            if (sopTaskCustomerVoList != null && !sopTaskCustomerVoList.isEmpty()) {
                for (SopTaskCustomerVo sopTaskCustomerVo : sopTaskCustomerVoList) {

                    //获取机器人微信昵称，头像
                    WwDevice wwDevice = wwDeviceMapper.getById(sopTaskCustomerVo.getDeviceUniqueId(), sopTaskCustomerVo.getMerId());
                    if (wwDevice != null) {
                        sopTaskCustomerVo.setDeviceName(wwDevice.getDeviceName());
                        sopTaskCustomerVo.setDeviceHeadImageUrl(wwDevice.getHeadImgUrl());
                    }


                    //获取客户
                    if (sopTaskCustomerVo.getType() != null && sopTaskCustomerVo.getType() == 0) {
                        WwCustomer wwCustomer = wwCustomerMapper.getByDeviceAndWxid(sopTaskCustomerVo.getWxid(), sopTaskCustomerVo.getDeviceUniqueId(), sopTaskCustomerVo.getMerId());
                        if (wwCustomer != null) {
                            sopTaskCustomerVo.setCustomerId(wwCustomer.getId());
                            sopTaskCustomerVo.setCustomerName(wwCustomer.getName());
                            sopTaskCustomerVo.setCustomerHeadImageUrl(wwCustomer.getHeadImgUrl());
                        }
                    }
                    //获取群
                    if (sopTaskCustomerVo.getType() != null && sopTaskCustomerVo.getType() == 1) {
                        WwGroup wwGroup = wwGroupMapper.selectByGroupWxId(sopTaskCustomerVo.getMerId(), sopTaskCustomerVo.getDeviceUniqueId(), sopTaskCustomerVo.getWxid());
                        if (wwGroup != null) {
                            sopTaskCustomerVo.setGroupId(wwGroup.getId());
                            sopTaskCustomerVo.setGroupName(wwGroup.getGroupName());
                            sopTaskCustomerVo.setGroupHeadImageUrl(wwGroup.getHeadImageUrl());
                        }

                    }
                }
                sopTaskVo.setSopTaskCustomerVoList(sopTaskCustomerVoList);
            }
        }


        return sopTaskVo;
    }


    @Override
    @Transactional(rollbackFor = Exception.class)
    public void delSopTask(SopTaskDto sopTaskDto) {
        if (sopTaskDto.getMerId() == null) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.MERID_NULL);
        }
        if (sopTaskDto.getId() == null) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.ID_NULL);
        }

        SopTask sopTask = sopTaskMapper.getById(sopTaskDto.getId(), sopTaskDto.getMerId());

        if (sopTask == null) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "该sop任务不存在");
        }

        //获取sop和机器人关系,删除
        SopTaskDeviceQuery sopTaskDeviceQuery = new SopTaskDeviceQuery();
        sopTaskDeviceQuery.setMerId(sopTask.getMerId());
        sopTaskDeviceQuery.setTaskId(sopTask.getId());
        List<SopTaskDeviceVo> sopTaskDeviceVoList = sopTaskDeviceMapper.getSopTaskDeviceList(sopTaskDeviceQuery);
        if (sopTaskDeviceVoList != null && !sopTaskDeviceVoList.isEmpty()) {
            sopTaskDeviceVoList.forEach(it -> sopTaskDeviceMapper.delById(it.getId(), it.getMerId()));
        }

        //获取sop和客户或者群的关系 删除
        SopTaskCustomerQuery sopTaskCustomerQuery = new SopTaskCustomerQuery();
        sopTaskCustomerQuery.setMerId(sopTask.getMerId());
        sopTaskCustomerQuery.setTaskId(sopTask.getId());
        List<SopTaskCustomerVo> sopTaskCustomerVoList = sopTaskCustomerMapper.getSopTaskCustomerList(sopTaskCustomerQuery);
        if (sopTaskCustomerVoList != null && !sopTaskCustomerVoList.isEmpty()) {
            sopTaskCustomerVoList.forEach(it -> sopTaskCustomerMapper.delById(it.getId(), it.getMerId()));
        }


        //删除sop 任务
        sopTaskMapper.delById(sopTask.getId(), sopTask.getMerId());
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void closeSopTask(CloseSopTaskDto closeSopTaskDto) {

        if (closeSopTaskDto.getMerId() == null) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.MERID_NULL);
        }
        if (closeSopTaskDto.getId() == null) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.ID_NULL);
        }
        if (closeSopTaskDto.getStatus() == null) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.PARAMETER_ERROR);
        }

        SopTask sopTask = sopTaskMapper.getById(closeSopTaskDto.getId(), closeSopTaskDto.getMerId());

        if (sopTask == null) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "该sop任务不存在");
        }

        //修改task状态
        sopTask.setStatus(closeSopTaskDto.getStatus());
        sopTaskMapper.update(sopTask);


        //修改job 状态
        SopJobQuery sopJobQuery = new SopJobQuery();
        sopJobQuery.setMerId(sopTask.getMerId());
        sopJobQuery.setTaskId(sopTask.getId());
        List<SopJobVo> sopJobVoList = sopJobMapper.getJobList(sopJobQuery);
        if (sopJobVoList != null && !sopJobVoList.isEmpty()) {
            for (SopJobVo sopJobVo : sopJobVoList) {
                SopJob sopJob = new SopJob();
                BeanUtil.copyProperties(sopJobVo, sopJob);
                sopJob.setStatus(closeSopTaskDto.getStatus());
                sopJobMapper.update(sopJob);
            }
        }

    }


    @Override
    public Object getSopTaskDeviceConfigList(WwDeviceQuery wwDeviceQuery) {

        if (wwDeviceQuery.getMerId() == null) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.MERID_NULL);
        }
        List<SopTaskDeviceConfigVo> sopTaskDeviceConfigVoList = new ArrayList<>();

        MyPageInfo<WwDeviceVo> wwDeviceVoMyPageInfo = wwDeviceService.getWwDevice(wwDeviceQuery);
        if (wwDeviceVoMyPageInfo.getRecords() != null && !wwDeviceVoMyPageInfo.getRecords().isEmpty()) {

            for (WwDeviceVo wwDeviceVo : wwDeviceVoMyPageInfo.getRecords()) {
                try {
                    SopTaskDeviceConfigVo sopTaskDeviceConfigVo = new SopTaskDeviceConfigVo();
                    sopTaskDeviceConfigVo.setMerId(wwDeviceVo.getMerId());
                    sopTaskDeviceConfigVo.setDeviceUniqueId(wwDeviceVo.getId());
                    sopTaskDeviceConfigVo.setDeviceId(wwDeviceVo.getDeviceId());
                    sopTaskDeviceConfigVo.setHeadImgUrl(wwDeviceVo.getHeadImgUrl());
                    sopTaskDeviceConfigVo.setDeviceName(wwDeviceVo.getDeviceName());

                    //获取配置
                    SopTaskDeviceConfig sopTaskDeviceConfig = sopTaskDeviceConfigMapper.getByDeviceUniqueId(wwDeviceVo.getId(), wwDeviceVo.getMerId());
                    if (sopTaskDeviceConfig != null) {
                        sopTaskDeviceConfigVo.setId(sopTaskDeviceConfig.getId());
                        sopTaskDeviceConfigVo.setRateMax(sopTaskDeviceConfig.getRateMax());
                        sopTaskDeviceConfigVo.setRateMin(sopTaskDeviceConfig.getRateMin());
                        sopTaskDeviceConfigVo.setSopDeviceRule(JSONObject.parseObject(sopTaskDeviceConfig.getRule(), SopDeviceRule.class));
                        sopTaskDeviceConfigVo.setCreateTime(sopTaskDeviceConfig.getCreateTime());
                        sopTaskDeviceConfigVo.setUpdateTime(sopTaskDeviceConfig.getUpdateTime());
                    }

                    sopTaskDeviceConfigVoList.add(sopTaskDeviceConfigVo);
                } catch (Exception e) {
                    e.printStackTrace();
                }

            }
        }
        MyPageInfo<SopTaskDeviceConfigVo> sopTaskDeviceConfigVoMyPageInfo = new MyPageInfo<>(sopTaskDeviceConfigVoList);
        sopTaskDeviceConfigVoMyPageInfo.setPages(wwDeviceVoMyPageInfo.getPages());
        sopTaskDeviceConfigVoMyPageInfo.setTotal(wwDeviceVoMyPageInfo.getTotal());
        sopTaskDeviceConfigVoMyPageInfo.setSize(wwDeviceVoMyPageInfo.getSize());
        sopTaskDeviceConfigVoMyPageInfo.setCurrent(wwDeviceVoMyPageInfo.getCurrent());
        return sopTaskDeviceConfigVoMyPageInfo;
    }


    @Override
    public void updateSopTaskDeviceConfig(SopTaskDeviceConfigDto sopTaskDeviceConfigDto) {
        if (sopTaskDeviceConfigDto.getMerId() == null) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.MERID_NULL);
        }
        if (sopTaskDeviceConfigDto.getDeviceUniqueId() == null) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.PARAMETER_ERROR);
        }

        if (sopTaskDeviceConfigDto.getId() == null) {
            //新建
            SopTaskDeviceConfig sopTaskDeviceConfig = new SopTaskDeviceConfig();
            BeanUtil.copyProperties(sopTaskDeviceConfigDto, sopTaskDeviceConfig);
            sopTaskDeviceConfig.setRule(JSONObject.toJSONString(sopTaskDeviceConfigDto.getSopDeviceRule()));
            sopTaskDeviceConfigMapper.add(sopTaskDeviceConfig);
        }
        if (sopTaskDeviceConfigDto.getId() != null) {
            //修改
            SopTaskDeviceConfig sopTaskDeviceConfig = sopTaskDeviceConfigMapper.getById(sopTaskDeviceConfigDto.getId(), sopTaskDeviceConfigDto.getMerId());

            if (sopTaskDeviceConfig != null) {
                BeanUtil.copyProperties(sopTaskDeviceConfigDto, sopTaskDeviceConfig);
                sopTaskDeviceConfig.setRule(JSONObject.toJSONString(sopTaskDeviceConfigDto.getSopDeviceRule()));
                sopTaskDeviceConfigMapper.update(sopTaskDeviceConfig);
            }
        }
    }


    @Override
    public Object getSopJobList(SopJobQuery sopJobQuery) {

        if (sopJobQuery.getMerId() == null) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.MERID_NULL);
        }

        if (!StringUtils.isBlank(sopJobQuery.getKeyword())) {
            WwDeviceQuery wwDeviceQuery = new WwDeviceQuery();
            wwDeviceQuery.setMerId(sopJobQuery.getMerId());
            wwDeviceQuery.setKeyword(sopJobQuery.getKeyword());
            List<WwDeviceVo> wwDeviceVoList = wwDeviceMapper.getWwDeviceList(wwDeviceQuery);
            if (wwDeviceVoList == null || wwDeviceVoList.isEmpty()) {
                return new MyPageInfo<>(null);
            }
            List<Long> deviceUniqueIds = wwDeviceVoList.stream().map(WwDeviceVo::getId).distinct().collect(Collectors.toList());
            sopJobQuery.setDeviceUniqueIds(deviceUniqueIds);

        }

        //通过模版名获取模版ID
        if (!StringUtils.isBlank(sopJobQuery.getTemplateName())) {
            //获取企业模版
            SopTemplateQuery sopTemplateQuery = new SopTemplateQuery();
            sopTemplateQuery.setMerId(sopTemplateQuery.getMerId());
            sopTemplateQuery.setName(sopJobQuery.getTemplateName());
            List<SopTemplateVo> sopTemplateList = sopTemplateMapper.getSopTemplateList(sopTemplateQuery);
            if (sopTemplateList == null || sopTemplateList.isEmpty()) {
                return new MyPageInfo<>(null);
            }
            List<Long> templateIds = sopTemplateList.stream().map(SopTemplateVo::getId).distinct().collect(Collectors.toList());
            sopJobQuery.setTemplateIds(templateIds);
        }


        String orderBy = OrderByUtil.getOrderBy(sopJobQuery.getOrderByField(), sopJobQuery.isAsc());
        PageHelper.startPage(sopJobQuery.getCurrent(), sopJobQuery.getSize(), orderBy);

        List<SopJobVo> jobList = sopJobMapper.getJobList(sopJobQuery);

        if (jobList != null && !jobList.isEmpty()) {
            for (SopJobVo sopJobVo : jobList) {
                try {

                    //获取模版名
                    SopTemplate sopTemplate = sopTemplateMapper.getById(sopJobVo.getTeaplateId(), sopJobVo.getMerId());
                    if (sopTemplate != null) {
                        sopJobVo.setTemplateName(sopTemplate.getName());
                    }


                    //获取机器人信息
                    WwDevice wwDevice = wwDeviceMapper.getById(sopJobVo.getDeviceUniqueId(), sopJobVo.getMerId());
                    if (wwDevice != null) {
                        sopJobVo.setDeviceName(wwDevice.getDeviceName());
                    }

                    //获取客户信息
                    if (sopJobVo.getWxidType() != null && sopJobVo.getWxidType() == 0) {
                        WwCustomer wwCustomer = wwCustomerMapper.getByDeviceAndWxid(sopJobVo.getWxid(), sopJobVo.getDeviceUniqueId(), sopJobVo.getMerId());
                        if (wwCustomer != null) {
                            sopJobVo.setCustomerId(wwCustomer.getId());
                            sopJobVo.setCustomerName(wwCustomer.getRemark() == null ? (wwCustomer.getName() == null ? null : wwCustomer.getName()) : wwCustomer.getRemark());
                            sopJobVo.setCustomerHeadImageUrl(wwCustomer.getHeadImgUrl());
                        }
                    }
                    //获取群信息
                    if (sopJobVo.getWxidType() != null && sopJobVo.getWxidType() == 1) {
                        WwGroup wwGroup = wwGroupMapper.getByGroupWxid(sopJobVo.getWxid(), sopJobVo.getDeviceId(), sopJobVo.getMerId());
                        if (wwGroup != null) {
                            sopJobVo.setGroupId(wwGroup.getId());
                            sopJobVo.setGroupName(wwGroup.getGroupName());
                            sopJobVo.setGroupHeadImageUrl(wwGroup.getHeadImageUrl());
                        }
                    }


                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }


        return new MyPageInfo<>(jobList);
    }


    @Override
    public void closeSopJob(SopJobDto sopJobDto) {

        if (sopJobDto.getMerId() == null) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.MERID_NULL);
        }
        if (sopJobDto.getId() == null) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.ID_NULL);
        }
        if (sopJobDto.getStatus() == null) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.PARAMETER_ERROR);
        }

        SopJob sopJob = sopJobMapper.getById(sopJobDto.getId(), sopJobDto.getMerId());

        if (sopJob == null) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "该任务不存在");
        }

        sopJob.setStatus(sopJobDto.getStatus());
        sopJobMapper.update(sopJob);

    }


    @Override
    public Object findAddFangetEffectuateGroupGroup(EffectuateGroupDto effectuateGroupDto) {

        if (effectuateGroupDto.getMerId() == null) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.MERID_NULL);
        }
        if (effectuateGroupDto.getPlanId() == null) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.PARAMETER_ERROR);
        }
        if (StringUtils.isBlank(effectuateGroupDto.getGroupPullKey())) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.PARAMETER_ERROR);
        }

        SopTemplate sopTemplate = sopTemplateMapper.getById(effectuateGroupDto.getPlanId(), effectuateGroupDto.getMerId());
        if (sopTemplate == null) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "该模版不存在");
        }

        if (StringUtils.isBlank(sopTemplate.getPlanDatas())) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "计划数据列表不存在");
        }

        List<PlanData> planDataList = JSONObject.parseArray(sopTemplate.getPlanDatas(), PlanData.class);
        if (planDataList == null || planDataList.isEmpty()) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "计划数据列表为空");
        }

        List<EffectuateGroupVo> effectuateGroupVoList = new ArrayList<>();
        for (PlanData planData : planDataList) {
            if (planData.getMsgDataList() != null && !planData.getMsgDataList().isEmpty()) {
                for (GroupPullData groupPullData : planData.getMsgDataList()) {
                    if (groupPullData.getMsgType() != null && groupPullData.getMsgType().equals(100)) {
                        if (!StringUtils.isBlank(groupPullData.getGroupPullKey()) && groupPullData.getGroupPullKey().equals(effectuateGroupDto.getGroupPullKey())) {

                            if (groupPullData.getGroupRules() != null && !groupPullData.getGroupRules().isEmpty()) {
                                effectuateGroupVoList = new ArrayList<>();
                                for (GroupRule groupRule : groupPullData.getGroupRules()) {
                                    EffectuateGroupVo effectuateGroupVo = new EffectuateGroupVo();
                                    effectuateGroupVo.setDeviceId(groupRule.getDeviceId());
                                    effectuateGroupVo.setDeviceUniqueId(groupRule.getDeviceUniqueId());
                                    effectuateGroupVo.setDeviceName(groupRule.getDeviceName());
                                    effectuateGroupVo.setDeviceHeadImageUrl(groupRule.getDeviceHeadImageUrl());
                                    if (groupRule.getGroupRuleInfos() != null && !groupRule.getGroupRuleInfos().isEmpty()) {
                                        List<GroupRuleInfoVo> groupRuleInfoVoList = new ArrayList<>();
                                        for (GroupRuleInfo groupRuleInfo : groupRule.getGroupRuleInfos()) {
                                            GroupRuleInfoVo groupRuleInfoVo = new GroupRuleInfoVo();
                                            groupRuleInfoVo.setDeviceId(groupRule.getDeviceId());
                                            groupRuleInfoVo.setDeviceUniqueId(groupRule.getDeviceUniqueId());
                                            groupRuleInfoVo.setDeviceName(groupRule.getDeviceName());
                                            groupRuleInfoVo.setGroupId(groupRuleInfo.getGroupId());
                                            groupRuleInfoVo.setGroupWxid(groupRuleInfo.getGroupWxid());
                                            groupRuleInfoVo.setGroupNick(groupRuleInfo.getGroupNick());
                                            groupRuleInfoVo.setGenders(groupRuleInfo.getGenders());
                                            groupRuleInfoVo.setDeviceHeadImageUrl(groupRule.getDeviceHeadImageUrl());
                                            groupRuleInfoVo.setGroupMemberNum((Integer) redisTemplate.opsForValue().get(String.format(RedisCacheKeyEnum.GROUP_MEMBER_COUNT.getKey(), groupRuleInfo.getGroupWxid())));
                                            groupRuleInfoVoList.add(groupRuleInfoVo);
                                        }
                                        effectuateGroupVo.setGroupRuleInfoVoList(groupRuleInfoVoList);
                                    }
                                    effectuateGroupVoList.add(effectuateGroupVo);
                                }

                            }
                        }
                    }
                }
            }
        }


        return effectuateGroupVoList;
    }
}
